<template>
  <div class="main">
    <div class="top">
      <button @click="back()" class="button">
        <div class="button-box">
          <span class="button-elem">
            <svg viewBox="0 0 46 40" xmlns="http://www.w3.org/2000/svg">
              <path
                d="M46 20.038c0-.7-.3-1.5-.8-2.1l-16-17c-1.1-1-3.2-1.4-4.4-.3-1.2 1.1-1.2 3.3 0 4.4l11.3 11.9H3c-1.7 0-3 1.3-3 3s1.3 3 3 3h33.1l-11.3 11.9c-1 1-1.2 3.3 0 4.4 1.2 1.1 3.3.8 4.4-.3l16-17c.5-.5.8-1.1.8-1.9z">
              </path>
            </svg>
          </span>
          <span class="button-elem">
            <svg viewBox="0 0 46 40">
              <path
                d="M46 20.038c0-.7-.3-1.5-.8-2.1l-16-17c-1.1-1-3.2-1.4-4.4-.3-1.2 1.1-1.2 3.3 0 4.4l11.3 11.9H3c-1.7 0-3 1.3-3 3s1.3 3 3 3h33.1l-11.3 11.9c-1 1-1.2 3.3 0 4.4 1.2 1.1 3.3.8 4.4-.3l16-17c.5-.5.8-1.1.8-1.9z">
              </path>
            </svg>
          </span>
        </div>
      </button>
      <span style="font-size: 25px;">
        修改草稿
      </span>
    </div>
    <div class="main-body">
      <el-form :model="form" label-width="auto" style="max-width: 900px">
        <el-form-item label="文章标题">
          <el-input v-model="form.title" />
        </el-form-item>
        <el-form-item label="文章封面">
          <el-upload class="avatar-uploader" :action="actionUrl" :show-file-list="false"
            :on-success="handleAvatarSuccess" :before-upload="beforeUpload">
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="文章状态">
          <el-select v-model="form.status" placeholder="请选择要保存文章的状态">
            <el-option v-for="item in statusOptions" 
            :key="item.value"
            :label="item.label" 
            :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="文章内容">
          <v-md-editor v-model="form.content" @upload-image="handleUploadImage()" height="500px">
          </v-md-editor>
        </el-form-item>
        <el-form-item>
          <el-button style="margin-left: 800px;" type="primary" @click="onSubmit()">保存或提交审核</el-button>
        </el-form-item>
      </el-form>

    </div>
  </div>
</template>

<script setup name="articles">
import { ref, reactive, onMounted ,computed} from 'vue';
import { ElMessageBox, ElMessage, ElNotification } from 'element-plus';
import config from '../../../../public/config'
import router from '../../../router'
import { getDetails ,updateArticle} from '../../../api/article';
import { useArticleStore } from '../../../stores/article';



const articleStore = new useArticleStore()
let actionUrl = config.uploadUrl
let imageUrl = ref('')


onMounted(() => {
  getArticleDetails()
})

const statusOptions = ref([
  { label: '私有', value: 2 },
  { label: '草稿', value: 0 },
  { label: '发布(提交审核)', value:3 },
  { label: '邀请协作', value: 5 }
]);

const form = reactive({
  id:'',
  title: '',
  status: '',
  content: '',
  pic: '',
  // userId: ''
})
function back() {
  ElMessageBox.confirm(
    '确定要退出吗？未保存的进度将丢失',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      router.back()
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消返回',
      })
    })
}
// 检查表单是否为空
function validateForm() {
  for (const key in form) {
    if (form[key] === '') {
      return false; // 如果发现空值，返回 false
    }
  }
  return true; // 所有字段都有值，返回 true
}
async function onSubmit() {
  // 提交前检查表单
  if (!validateForm()) {
    ElNotification({
      title: '检查',
      message: '您还没有完成所有内容，内容不能有空',
      type: 'error',
      showClose: false,
    });
    return; // 阻止提交
  }
  await updateArticle(form)
    .then(res => {
      if (res.code === 200) {
        ElNotification({
          title: '成功',
          message: res.data,
          type: 'success',
          showClose: false,
        });
        router.back()
      }
      else {
        ElNotification({
          title: '失败',
          message: res.data,
          type: 'error',
          showClose: false,
        });
      }
    })
}

//图片上传成功后的方法
function handleAvatarSuccess(response, file, fileList) {
  imageUrl.value = `${config.downloadUrl}?name=${response.data}`
  form.pic = response.data
}
//上传图片之前
function beforeUpload(file) {
  if (file) {
    const suffix = file.name.split('.')[1]
    const size = file.size / 1024 / 1024 < 2
    if (['png', 'jpeg', 'jpg'].indexOf(suffix) < 0) {
      ElMessage({
        type: 'info',
        message: '上传图片只支持 png、jpeg、jpg 格式！',
      })
      // this.$message.error('上传图片只支持 png、jpeg、jpg 格式！')
      // this.$refs.upload.clearFiles()
      return false
    }
    if (!size) {
      ElMessage({
        type: 'info',
        message: '上传文件大小不能超过 2MB!',
      })
      // this.$message.error('上传文件大小不能超过 2MB!')
      return false
    }
    return file
  }
}

async function getArticleDetails() {
  const params = new URLSearchParams
  params.append("id", articleStore.articleId)
  await getDetails(params).then(res => {
    if (res.code === 200) {
      const data = res.data
      form.title = data.title
      form.status = data.status
      // form.userId = data.userId
      form.content = data.content
      form.pic = data.pic
      form.id = articleStore.articleId
      imageUrl.value = `${config.downloadUrl}?name=${data.pic}`
    }
  })
}
</script>

<style scoped>
.main {
  width: 100%;
  display: flex;
  flex-direction: column;
}

.top {
  display: flex;
  flex-direction: row;
  align-items: center
}

.main-body {
  margin-top: 20px;
  display: flex;
  flex-direction: column;
}

.button {
  display: block;
  position: relative;
  width: 56px;
  height: 56px;
  margin: 0;
  overflow: hidden;
  outline: none;
  background-color: transparent;
  cursor: pointer;
  border: 0;
}

.button:before,
.button:after {
  content: "";
  position: absolute;
  border-radius: 50%;
  inset: 7px;
}

.button:before {
  border: 4px solid #0d2ad2;
  transition: opacity 0.4s cubic-bezier(0.77, 0, 0.175, 1) 80ms,
    transform 0.5s cubic-bezier(0.455, 0.03, 0.515, 0.955) 80ms;
}

.button:after {
  border: 4px solid #040013;
  transform: scale(1.3);
  transition: opacity 0.4s cubic-bezier(0.165, 0.84, 0.44, 1),
    transform 0.5s cubic-bezier(0.25, 0.46, 0.45, 0.94);
  opacity: 0;
}

.button:hover:before,
.button:focus:before {
  opacity: 0;
  transform: scale(0.7);
  transition: opacity 0.4s cubic-bezier(0.165, 0.84, 0.44, 1),
    transform 0.5s cubic-bezier(0.25, 0.46, 0.45, 0.94);
}

.button:hover:after,
.button:focus:after {
  opacity: 1;
  transform: scale(1);
  transition: opacity 0.4s cubic-bezier(0.77, 0, 0.175, 1) 80ms,
    transform 0.5s cubic-bezier(0.455, 0.03, 0.515, 0.955) 80ms;
}

.button-box {
  display: flex;
  position: absolute;
  top: 0;
  left: 0;
}

.button-elem {
  display: block;
  width: 20px;
  height: 20px;
  margin: 17px 18px 0 18px;
  transform: rotate(180deg);
  fill: #190a65;
}

.button:hover .button-box,
.button:focus .button-box {
  transition: 0.4s;
  transform: translateX(-56px);
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>